import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

/**
 * 密码修改
 */
@Component({
  selector: 'app-security-changepwd',
  templateUrl: './change-pwd.component.html',
})
export class ChangePwdComponent implements OnInit {
  constructor(
    public http: _HttpClient,
    private notice: NzNotificationService,
    private msg: NzMessageService,
    private cdr: ChangeDetectorRef,
    private setting: SettingsService,
    fb: FormBuilder,
  ) {
    this.form = fb.group({
      password: [null, [Validators.required]],
      newpassword1: [null, [Validators.required, Validators.minLength(6), ChangePwdComponent.checkPassword.bind(this)]],
      newpassword2: [null, [Validators.required, Validators.minLength(6), ChangePwdComponent.passwordEquar]],
    });
  }
  status: 'pool' | 'ok' | 'pass' = 'pool';
  visible = false;
  progress = 0;
  user;
  passwordProgressMap = {
    ok: 'success',
    pass: 'normal',
    pool: 'exception',
  };
  form: FormGroup;

  static checkPassword(control: FormControl) {
    if (!control) return null;
    const self: any = this;
    self.visible = !!control.value;
    if (control.value && control.value.length > 9) {
      self.status = 'ok';
    } else if (control.value && control.value.length > 5) {
      self.status = 'pass';
    } else {
      self.status = 'pool';
    }

    if (self.visible) {
      self.progress = control.value.length * 10 > 100 ? 100 : control.value.length * 10;
    }
  }

  static passwordEquar(control: FormControl) {
    if (!control || !control.parent) {
      return null;
    }
    if (control.value !== control.parent.get('newpassword1')!.value) {
      return { equar: true };
    }
    return null;
  }

  ngOnInit() {
    this.http.get(`/cf/admin/user/${this.setting.user.userId}`).subscribe(res => {
      this.user = res.data;
    });
  }

  save() {
    Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      this.form.controls[key].updateValueAndValidity();
    });
    if (this.form.invalid) {
      return;
    }

    const data = this.form.value;
    this.user.newpassword1 = data.newpassword1;
    this.user.password = data.password;
    this.http.put(`/cf/admin/user/edit`, this.user).subscribe(res => {
      if (res.status === 200) {
        this.notice.success('成功', '密码修改成功');
      }
      this.form.reset();
    });
  }
}
